﻿/**************************************************************************
创建时间:	2020/6/28
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using ZhCun.DbCore.BuildSQLText;
using ZhCun.DbCore.Cores;
using ZhCun.DbCore.Entitys;
using ZhCun.Utils;
using ZhCun.Utils.Helpers;
using ZhCun.WebUtils.Authorizes;

namespace ZhCun.WebUtils.DB
{
    public interface ILoginSessionSet
    {
        void SetLoginSession(ILoginSession session);
    }

    public class BLLBase : IApiResultExtend, ILoginSessionSet
    {
        public BLLBase()
        {

        }

        public BLLBase(string connStr)
        {
            _ConnStr = connStr;
        }

        DBMain _DB;
        string _ConnStr;

        protected void SetConnStr(string connStr)
        {
            this._ConnStr = connStr;
        }

        public virtual DBMain DB
        {
            get
            {
                if (_DB == null)
                {
                    _DB = CreateDB();
                }
                return _DB;
            }
        }
        /// <summary>
        /// 创建DB对象，用于BLL中异步处理，不使用相同DB对象
        /// </summary>
        public DBMain CreateDB()
        {
            DBMain db;
            if (_ConnStr == null)
            {
                db = new DBMain();
            }
            else
            {
                db = new DBMain(_ConnStr);
            }
            return db;
        }

        public void SetLoginSession(ILoginSession session)
        {
            DB.LoginSession = session;
        }
        /// <summary>
        /// 当前登陆用户Id
        /// </summary>
        public string CurrUserId
        {
            get
            {
                return DB.LoginSession?.CurrUser?.UserId;
            }
        }
        /// <summary>
        /// 当前用户名
        /// </summary>
        public string CurrUserName
        {
            get
            {
                return DB.LoginSession?.CurrUser?.UserName;
            }
        }
        /// <summary>
        /// 当前登陆用户角色Id
        /// </summary>
        public string CurrRoleId
        {
            get
            {
                return DB.LoginSession?.CurrUser?.RoleId;
            }
        }
        /// <summary>
        /// 当前科室（部门）Id
        /// </summary>
        public string CurrDeptId
        {
            get
            {
                return DB.LoginSession?.CurrUser?.DeptId;
            }
        }
        /// <summary>
        /// 当前科室（部门）名称
        /// </summary>
        public string CurrDeptName
        {
            get
            {
                return DB.LoginSession?.CurrUser?.DeptName;
            }
        }
        /// <summary>
        /// 返回当前用户的客户端Id
        /// </summary>
        public int CurrClientId
        {
            get
            {
                return DB.LoginSession?.CurrUser?.ClientId ?? 0;
            }
        }
        /// <summary>
        /// 是否管理员登陆
        /// </summary>
        public bool IsManager => DB.LoginSession?.CurrUser?.IsManager ?? false;

        /// <summary>
        /// 创建一个自定义Guid
        /// </summary>
        public string NewId()
        {
            return GuidHelper.NewId();
        }

        public DateTime GetNowTime()
        {
            return DateTime.Now;
        }

        public virtual void WriteLog(string log)
        {
            //TODO: 写入数据库日志
        }

        public virtual ApiResultList<TEntity> GetPagerList<TEntity>(ArgPageData arg, Action<QueryCondition<TEntity>> QueryHandle)
            where TEntity : EntityBase, new()
        {
            var rList = GetPagerList(arg, out int total, QueryHandle);

            return RetOK(rList, total);
        }

        public virtual List<TEntity> GetPagerList<TEntity>(ArgPageData arg, out int total, Action<QueryCondition<TEntity>> QueryHandle)
            where TEntity : EntityBase, new()
        {
            var query = DB.CreateQuery<TEntity>();
            query.PageNo = arg.PageNo;
            query.PageSize = arg.PageSize;
            QueryHandle?.Invoke(query);
            var adSql = GetAdSearchSql(arg.AdSearchList);
            var rList = DB.Query<TEntity>(query, adSql).ToList(true);
            total = query.Total;
            return rList;
        }

        public virtual List<TEntity> GetPagerList<TEntity>(int pageNo, int pageSize, out int total, Action<QueryCondition<TEntity>> QueryHandle)
            where TEntity : EntityBase, new()
        {
            return GetPagerList<TEntity>(new ArgPageData
            {
                PageNo = pageNo,
                PageSize = pageSize
            }, out total, QueryHandle);
        }

        #region 返回结果的创建及定义

        /// <summary>
        /// 成功结果，可指定成功消息
        /// </summary>
        public ApiResult RetOK(string msg = null)
        {
            return ApiResult.RetOK(msg);
        }
        /// <summary>
        /// 成功结果，并返回实体对象的结果
        /// </summary>
        public ApiResult<T> RetOK<T>(T data, string msg = "")
        {
            return ApiResult.RetOK(data, msg);
        }

        /// <summary>
        /// 返回一个实体集合结果
        /// </summary>
        public ApiResultList<T> RetOK<T>(List<T> data, int count, string msg = "")
        {
            return ApiResult.RetOK(data, count, msg);
        }
        /// <summary>
        /// 返回空的 List 数据
        /// </summary>
        public ApiResultList<T> RetNullData<T>(string msg)
        {
            return new ApiResultList<T>() { code = ApiResult.CODE_VERIFY_FAIL, msg = msg };
        }
        /// <summary>
        /// 正常逻辑错误
        /// </summary>
        public ApiResult RetErr(string msg)
        {
            return ApiResult.RetErr(msg);
        }
        /// <summary>
        /// 返回数据对象的错误结果
        /// </summary>
        public ApiResult<T> RetErr<T>(string msg)
        {
            return ApiResult.RetErr<T>(msg);
        }
        ///// <summary>
        ///// 返回验证错误,data 表示属性名称
        ///// </summary>
        //public ApiResult<string> RetErr(string propertyName, string msg)
        //{
        //    return ApiResult.RetErr(propertyName, msg);
        //}
        /// <summary>
        /// 返回验证错误,data 表示属性名称
        /// </summary>
        public ApiResult<T> RetErr<T>(T t, string msg)
        {
            return new ApiResult<T>() { data = t, code = ApiResult.CODE_VERIFY_FAIL, msg = msg };
        }

        #endregion

        /// <summary>
        /// 获取高级搜索sqlBuiler
        /// </summary>
        public ISqlBuilder GetAdSearchSql(List<AdSearchDetail> searchList)
        {
            if (searchList == null || searchList.Count == 0)
            {
                return null;
            }
            ISqlBuilder sql = DB.CreateSqlBuilder("AD");
            foreach (var item in searchList)
            {
                sql.AddSQLText($" {item.ConnectorSignStr}");
                sql.AddSQLText($" {item.FieldName}");
                sql.AddSQLText($" {item.CompareSignStr}");
                var dataType = ConvertData.GetTypeByString(item.DataTypeStr);
                object val = Convert.ChangeType(item.SearchValue, dataType);
                sql.AddSQLParam(" {0}", val);
            }
            return sql;
        }
    }
}